<script setup lang="ts">
import { computed } from 'vue'
import { useEditorStore } from '@/stores/editor'
import { componentRegistry } from '@/core/ComponentRegistry'

const store = useEditorStore()

const customComponents = computed(() => {
  return componentRegistry.getAll().map(item => ({
    type: 'custom',
    component: item.meta.name,
    label: item.meta.label,
    icon: item.meta.icon || '🧩'
  }))
})

const allComponents = computed(() => [
  { type: 'button', label: '按钮', icon: '🔘' },
  { type: 'input', label: '输入框', icon: '📝' },
  { type: 'container', label: '容器', icon: '📦' },
  { type: 'grid', label: '栅格', icon: '📐' },
  { type: 'tabs', label: '选项卡', icon: '📑' },
  ...customComponents.value
])

// 提取 key 逻辑以保证类型安全
const getKey = (item: { type: string; component?: string }) => {
  return `${item.type}-${item.component || ''}`
}

const onDragStart = (item: any, event: DragEvent) => {
  const data = JSON.stringify({
    type: item.type,
    component: item.component
  })
  if (event.dataTransfer) {
    event.dataTransfer.setData('text/plain', data)
    event.dataTransfer.effectAllowed = 'copy'
  }
}

</script>

<template>
  <div class="component-library">
    <h3>组件库</h3>
    <div class="components">
      <div
        v-for="item in allComponents"
        :key="getKey(item)"
        class="component-item"
        draggable="true"
        @dragstart="onDragStart(item, $event)"
      >
        {{ item.icon || '' }} {{ item.label }}
      </div>
    </div>
  </div>
</template>

<style scoped>
.component-library {
  width: 200px;
  border-right: 1px solid #ddd;
  padding: 16px;
}
.components { display: flex; flex-direction: column; gap: 8px; }
.component-item {
  padding: 8px;
  border: 1px solid #eee;
  border-radius: 4px;
  cursor: move;
}
</style>
